package com.sds.session.service;

import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.Cookie;

import org.springframework.stereotype.Service;

import com.sds.session.util.CookieUtil;

@Service
public class IDPSessionService {
	
	public Cookie[] createSession(String domain, String userId, String userIP) throws Exception {
		URL url = new URL(domain + "/session/createSession.do");
		
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setRequestProperty("userId", userId);
		urlConn.setRequestProperty("userIP", userIP);
		
		urlConn.getInputStream();
		String cookieString = urlConn.getHeaderField("Set-Cookie");
		return CookieUtil.getCookieInstance(cookieString);
	}
	
	public boolean checkSession(String domain, String userId, String userIP, Cookie[] cookie) throws Exception {
		URL url = new URL(domain + "/session/checkSession.do");
		
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		urlConn.setRequestMethod("POST");
		urlConn.setRequestProperty("Cookie", CookieUtil.getCookieString(cookie));
		urlConn.setRequestProperty("userId", userId);
		urlConn.setRequestProperty("userIP", userIP);
		
		urlConn.getInputStream();
		String checkResult = urlConn.getHeaderField("CheckResult");
		if( "true".equals(checkResult) ) {
			return true;
		}
		return false;
	}
}
